package org.flashamaphone.buffer
{
	import flash.utils.ByteArray;
	
	import org.flashamaphone.controller.ISoundController;

	/**
	 * recorded buffer just saves bytes from the sound controller
	 */
	public class RecordedBuffer implements IBuffer
	{
		/** sound buffer */
		protected var _buffer:ByteArray = new ByteArray();
		
		/** sound controller */
		protected var _controller:ISoundController;
		
		/**
		 * c-tor
		 */
		public function RecordedBuffer(){}
		
		/**
		 * get if sound is active
		 * 
		 * @return active status
		 */
		public function get active():Boolean {
			if (_controller) {
				return true;
			} else {
				return false;
			}
		}
		
		/** 
		 * turn on buffer, there are pending bytes to play
		 */
		public function activateBuffer(controller:ISoundController):void {
			_controller = controller;
		}
		
		/**
		 * manually pull bytes from controller
		 * 
		 * @param num samples to pull
		 */
		public function pullFromController(samples:int):void {
			var pushtobuffer:ByteArray = _controller.pull(samples);
			pushtobuffer.position = 0;
			if (pushtobuffer.bytesAvailable > 0) {
				_buffer.position = _buffer.length;
				_buffer.writeBytes(pushtobuffer);
			}
		}
		
		/**
		 * get buffer bytes
		 * 
		 * @return byte array
		 */
		public function get buffer():ByteArray {
			_buffer.position = 0;
			return _buffer;
		}
		
		/**
		 * add bytes to buffer
		 *
		 * @param bytes to add
		 */
		public function addToBuffer(value:ByteArray):void {
			_buffer.writeBytes(value, _buffer.length-1);
		}
		
		/**
		 * clear buffer
		 */
		public function clearBuffer():void {
			_buffer.clear();
			_buffer.position = 0;
		}
	}
}